//
//  RealNameAuthenticationViewController.m
//  Btpin
//
//  Created by Vic on 2019/4/9.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "RealNameAuthenticationViewController.h"
#import "NSString+LY.h"
#import "RealNameAuthenticationModel.h"

@interface RealNameAuthenticationViewController ()<UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, PSSingleRowViewDelegate>
{
    RealNameAuthenticationModel *infoModel;
    
    PSSingleRowView *headerPickerView;
    
    BOOL zhengOrfanFlag; // yes:正
    NSString *zhengURL;
    NSString *fanURL;
}
@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *IDTextField;
@property (nonatomic, strong) UIImageView *cardImage;
@property (nonatomic, strong) UIImageView *cardfanmianImage;

/**
 图片选择控制器
 */
@property (nonatomic, strong) UIImagePickerController *picker;

/**
 头像
 */
@property (nonatomic, strong) UIImage *upCardImages;

@end

@implementation RealNameAuthenticationViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (headerPickerView) {
        headerPickerView.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"实名认证";
    
    [self loadDataLocation];
    [self loadData];
//    [self initUI];
}
- (void)loadData {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [BaseNetManager requestWithMethod:POST path:User_GetRealnameInfo_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDDismiss;
            
            self->infoModel = [[RealNameAuthenticationModel alloc] init];
            [self->infoModel setValuesForKeysWithDictionary:responseObject[@"data"]];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
        [self initUI];
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)loadDataLocation {
    zhengURL = @"";
    fanURL = @"";
    zhengOrfanFlag = YES;
    
    NSMutableArray *headerArray = [NSMutableArray arrayWithCapacity:0];
    PublicCategoryElementModel *model1 = [[PublicCategoryElementModel alloc] init];
    [model1 setValuesForKeysWithDictionary:@{@"id":@"0", @"name":@"拍摄"}];
    [headerArray addObject:model1];
    PublicCategoryElementModel *model2 = [[PublicCategoryElementModel alloc] init];
    [model2 setValuesForKeysWithDictionary:@{@"id":@"1", @"name":@"相册"}];
    [headerArray addObject:model2];
    headerPickerView = [[PSSingleRowView alloc] initWithData:headerArray target:self];
    headerPickerView.hidden = YES;
}
- (void)initUI {
    UIScrollView *bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height)];
    [self.view addSubview:bottomScrollView];
    
    UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 70, 45)];
    newLabel.text = @"姓名";
    newLabel.font = [UIFont systemFontOfSize:13];
    newLabel.textColor = RGB(34, 34, 34);
    [bottomScrollView addSubview:newLabel];
    
    self.nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(newLabel.right + 5, newLabel.top, WIDTH - newLabel.right - 15, 45)];
    self.nameTextField.placeholder = @"请输入真实姓名";
    self.nameTextField.textColor = RGB(34, 34, 34);
    self.nameTextField.font = [UIFont systemFontOfSize:14];
    self.nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [bottomScrollView addSubview:self.nameTextField];
    if (infoModel && infoModel.realname) {
        self.nameTextField.text = infoModel.realname;
    }
    
    UIView *newLine = [[UIView alloc] initWithFrame:CGRectMake(0, newLabel.bottom, WIDTH, lineH)];
    newLine.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
    [bottomScrollView addSubview:newLine];
    
    UILabel *sureLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, newLine.bottom, 70, 45)];
    sureLabel.text = @"身份证号";
    sureLabel.font = [UIFont systemFontOfSize:14];
    sureLabel.textColor = RGB(34, 34, 34);
    [bottomScrollView addSubview:sureLabel];
    
    self.IDTextField = [[UITextField alloc] initWithFrame:CGRectMake(sureLabel.right + 5, sureLabel.top, WIDTH - sureLabel.right - 15, 45)];
    self.IDTextField.placeholder = @"请输入身份证号";
    self.IDTextField.textColor = RGB(34, 34, 34);
    self.IDTextField.font = [UIFont systemFontOfSize:13];
    self.IDTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [bottomScrollView addSubview:self.IDTextField];
    if (infoModel && infoModel.idcard) {
        self.IDTextField.text = infoModel.idcard;
    }
    
    UIView *sureLine = [[UIView alloc] initWithFrame:CGRectMake(0, sureLabel.bottom, WIDTH, 8)];
    sureLine.backgroundColor = RGB(247, 247, 247);
    [bottomScrollView addSubview:sureLine];
    
    UILabel *alertLbl = [UIToolsControl initLabelWithFrame:CGRectMake(LeftSpace, EndY(sureLine), WIDTH-30*Scale, 45*Scale) text:@"请您放心填写，数据将采用加密存储。" textColor:THEMECOLOR_OF_RED font:Font_12];
    [bottomScrollView addSubview:alertLbl];
    
    UIButton *verifiybtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(alertLbl) + 100*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(verifiybtnClick:) title:@"认证" titleColor:COLOR_OF_WHITE];
    verifiybtn.layer.cornerRadius = 23*Scale;
    verifiybtn.layer.masksToBounds = YES;
    verifiybtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    verifiybtn.userInteractionEnabled = YES;
    verifiybtn.titleLabel.font = Font(Font_17);
    [bottomScrollView addSubview:verifiybtn];
    
    bottomScrollView.contentSize = CGSizeMake(0, EndY(verifiybtn)+20*Scale);
    
    if (infoModel && [infoModel.audit isEqualToString:@"1"]) {
        [verifiybtn setTitle:@"通过认证" forState:UIControlStateNormal];
        verifiybtn.userInteractionEnabled = NO;
        verifiybtn.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
        [verifiybtn setTitleColor:THEMECOLOR_OF_RED forState:UIControlStateNormal];
        [verifiybtn setTitle:@"已认证" forState:UIControlStateNormal];
        
        self.nameTextField.userInteractionEnabled = NO;
        self.IDTextField.userInteractionEnabled = NO;
    }
    
    /*
    UILabel *uploadLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, sureLine.bottom, 100, 40)];
    uploadLabel.text = @"上传身份证";
    uploadLabel.font = [UIFont systemFontOfSize:13];
    uploadLabel.textColor = RGB(34, 34, 34);
    [bottomScrollView addSubview:uploadLabel];
    
    
    self.cardImage = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH - 180)/2, uploadLabel.bottom, 180, 120)];
    self.cardImage.image = [UIImage imageNamed:@"xinyong-shenfen"];
    self.cardImage.userInteractionEnabled = YES;
    [bottomScrollView addSubview:self.cardImage];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardImageClick:)];
    [self.cardImage addGestureRecognizer:tap];
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, self.cardImage.bottom+10, WIDTH - 30, 15)];
    messageLabel.text = @"+正面上传";
    messageLabel.font = [UIFont systemFontOfSize:12];
    messageLabel.textColor = [UIColor orangeColor];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    [bottomScrollView addSubview:messageLabel];
    if (infoModel && infoModel.idcard_front) {
        [self.cardImage sd_setImageWithURL:[NSURL URLWithString:infoModel.idcard_front] placeholderImage:[UIImage imageNamed:@"xinyong-shenfen"]];
    }
    
    self.cardfanmianImage = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH - 180)/2, messageLabel.bottom + 10, 180, 120)];
    self.cardfanmianImage.image = [UIImage imageNamed:@"xinyong-shenfen"];
    self.cardfanmianImage.userInteractionEnabled = YES;
    [bottomScrollView addSubview:self.cardfanmianImage];
    UITapGestureRecognizer *tapFan = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardfanmianImageClick:)];
    [self.cardfanmianImage addGestureRecognizer:tapFan];
    UILabel *messageLbl = [[UILabel alloc] initWithFrame:CGRectMake(15, self.cardfanmianImage.bottom+10, WIDTH - 30, 15)];
    messageLbl.text = @"+反面上传";
    messageLbl.font = [UIFont systemFontOfSize:12];
    messageLbl.textColor = [UIColor orangeColor];
    messageLbl.textAlignment = NSTextAlignmentCenter;
    [bottomScrollView addSubview:messageLbl];
    if (infoModel && infoModel.idcard_back) {
        [self.cardfanmianImage sd_setImageWithURL:[NSURL URLWithString:infoModel.idcard_back] placeholderImage:[UIImage imageNamed:@"xinyong-shenfen"]];
    }
    
    UILabel *lbl = [UIToolsControl initLabelWithFrame:CGRectMake(30*Scale, EndY(messageLbl)+10*Scale, WIDTH-60*Scale, 10*Scale) text:nil textColor:THEMECOLOR_OF_RED font:Font_13];
    lbl.numberOfLines = 0;
    lbl.lineBreakMode = NSLineBreakByWordWrapping;
    [bottomScrollView addSubview:lbl];
    if (infoModel && infoModel.audit && ([infoModel.audit integerValue] == 3)) {
        lbl.text = infoModel.audit_note;
        lbl.frame = CGRectMake(30*Scale, EndY(messageLbl)+10*Scale, WIDTH-60*Scale, 50*Scale);
    }
    
    UIButton *verifiybtn = [UIButton buttonWithType:UIButtonTypeCustom];
    verifiybtn.frame = CGRectMake( 40, EndY(lbl) + 30, WIDTH-80, 40);
    verifiybtn.layer.cornerRadius = verifiybtn.height/2;
    verifiybtn.clipsToBounds = YES;
    verifiybtn.backgroundColor = [UIColor orangeColor];
    verifiybtn.userInteractionEnabled = NO;
    [verifiybtn setTitle:@"认证" forState:UIControlStateNormal];
    [verifiybtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    verifiybtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [verifiybtn addTarget:self action:@selector(verifiybtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomScrollView addSubview:verifiybtn];
    
    if (infoModel && infoModel.audit && ([infoModel.audit integerValue] != 3)) {
        verifiybtn.userInteractionEnabled = NO;
        self.cardImage.userInteractionEnabled = NO;
        self.cardfanmianImage.userInteractionEnabled = NO;
    } else {
        verifiybtn.userInteractionEnabled = YES;
        self.cardImage.userInteractionEnabled = YES;
        self.cardfanmianImage.userInteractionEnabled = YES;
    }
    
    bottomScrollView.contentSize = CGSizeMake(0, EndY(verifiybtn)+20*Scale);
    */
}

#pragma mark --  UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString *multStr = [NSMutableString stringWithString:textField.text];
    [multStr replaceCharactersInRange:range withString:string];
    if (textField == self.IDTextField && multStr.length > 18) {
        return NO;
    } else {
        return YES;
    }
}
#pragma mark -- Action
- (void)verifiybtnClick:(UIButton *)button {
    [self.nameTextField resignFirstResponder];
    [self.IDTextField resignFirstResponder];
    
    if (self.nameTextField.text.length) {
        if (self.IDTextField.text.length && [UIToolsControl validateIDCard:self.IDTextField.text]) {
            
            [self upDate];
            
//            if (zhengURL) {
//                if (fanURL) {
//                    [self upDate];
//                } else {
//                    SVPHUDError(@"请上传身份证反面");
//                }
//            } else {
//                SVPHUDError(@"请上传身份证正面");
//            }
        } else {
            SVPHUDError(IDOKAlertText);
        }
    } else {
        SVPHUDError(NameAlertText);
    }
}
- (void)upDate {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:self.nameTextField.text forKey:@"realname"];
    [dic setObject:self.IDTextField.text forKey:@"idcard"];
//    [dic setObject:zhengURL forKey:@"idcard_front"];
//    [dic setObject:fanURL forKey:@"idcard_back"];
    
    [BaseNetManager requestWithMethod:POST path:User_SaveRealnameInfo_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            
            UD_SetOForK(self.nameTextField.text, isRealName);
            self.setok(self.nameTextField.text);
            
            [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)delayClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)cardImageClick:(UITapGestureRecognizer *)tap{
    headerPickerView.hidden = NO;
    zhengOrfanFlag = YES;
}
- (void)cardfanmianImageClick:(UITapGestureRecognizer *)tap{
    headerPickerView.hidden = NO;
    zhengOrfanFlag = NO;
}
- (void)psSingleRowViewCancel:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
}
- (void)psSingleRowViewOk:(PublicCategoryElementModel *)model PSSingleRowView:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
    if (psSingleRowView == headerPickerView) {
        if ([model.id integerValue] == 1) { // 相册
            [self openPhotoLibrary];
        } else { // 拍摄
            [self openCamera];
        }
    }
}
- (void)openCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (void)openPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相册权限未开启" message:@"相册权限未开启，请进入系统【设置】>【隐私】>【相册】中打开开关,开启相册功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = NO;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"finish..");
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    SVPHUDShow;
    [DataToolsControl uploadImgType:UploadImgTypeOfIDCard image:image successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            if (self->zhengOrfanFlag) {
                self->zhengURL = data[@"url"];
                self.cardImage.image = image;
            } else {
                self->fanURL = data[@"url"];
                self.cardfanmianImage.image = image;
            }
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(@"上传失败，请重新操作");
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
- (void)takePhoto {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = YES;
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_picker animated:YES completion:nil];
    }
}

- (void)choosePhoto {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = YES;
        //打开相册选择照片
        _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [_picker.navigationBar setShadowImage:[UIImage new]];
        NSDictionary *textAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
        [_picker.navigationBar setTitleTextAttributes:textAttributes];
        [_picker.navigationBar setTintColor:[UIColor whiteColor]];
        [_picker.navigationBar setBarTintColor:[UIColor blackColor]];
        
        [self.navigationController presentViewController:_picker animated:YES completion:^{
            
        }];
    }
}

#pragma mark -- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.upCardImages = [info objectForKey:UIImagePickerControllerEditedImage];
    self.cardImage.image = self.upCardImages;
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark -- NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //关闭相册界面
    [_picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //修改失败
    
}
*/

@end
